package com.dycloud.project.config;


import cn.hutool.core.util.StrUtil;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author : renhang
 * @description RedissonConfig
 * @date : 2025-05-28 14:58
 **/
@Configuration
public class RedissonConfig {

    private static final String ADDRESS_PREFIX = "redis://";

    private final RedisProperties redisProperties;

    @Autowired
    public RedissonConfig(RedisProperties redisProperties) {
        this.redisProperties = redisProperties;
    }

    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        if (Objects.isNull(redisProperties.getCluster())) {
            SingleServerConfig singleServerConfig = config.useSingleServer();
            singleServerConfig.setAddress(String.format("%s%s:%s", ADDRESS_PREFIX, redisProperties.getHost(), redisProperties.getPort()));
            singleServerConfig.setDatabase(redisProperties.getDatabase());
            if (StrUtil.isNotBlank(redisProperties.getPassword())) {
                singleServerConfig.setPassword(redisProperties.getPassword());
            }
            return Redisson.create(config);
        }
        List<String> clusters = redisProperties.getCluster().getNodes();
        if (Objects.nonNull(clusters) && !clusters.isEmpty()) {
            ClusterServersConfig clusterServersConfig = config.useClusterServers();
            List<String> clusterNodes = new ArrayList<>();
            for (String cluster : clusters) {
                clusterNodes.add(ADDRESS_PREFIX + cluster);
            }
            clusterServersConfig.setNodeAddresses(clusterNodes);
            if (StrUtil.isNotBlank(redisProperties.getPassword())) {
                clusterServersConfig.setPassword(redisProperties.getPassword());
            }
        }
        return Redisson.create(config);
    }
}
